//
//  HRNewFeatureView.swift
//  微博
//
//  Created by 众力金融 on 2017/1/13.
//  Copyright © 2017年 众力金融. All rights reserved.
//

import UIKit

class HRNewFeatureView: UIView {

    @IBOutlet weak var scrollview: UIScrollView!

    @IBOutlet weak var enterButton: UIButton!

    @IBOutlet weak var pageControl: UIPageControl!
    
    
    
    
   //进入微博
    @IBAction func enterclick(_ sender: Any) {
        
        removeFromSuperview()
    }
    
    
    class func FeatureView() -> HRNewFeatureView {
        let nib = UINib(nibName: "HRNewFeatureView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! HRNewFeatureView
        v.frame = UIScreen.main.bounds
        return v
    }
    
    //    override init(frame: CGRect) {
    //  super.init(frame: frame)
//        backgroundColor = UIColor.orange
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
    
    override func awakeFromNib() {
        //如果使用自动布局 从XIB加载默认是 600 * 600大小
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            let iv = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
            //设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollview.addSubview(iv)
            
            scrollview.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
            scrollview.bounces = false
            scrollview.isPagingEnabled = true
            scrollview.showsVerticalScrollIndicator = false
            scrollview.showsHorizontalScrollIndicator = false
            scrollview.delegate = self
            //隐藏按钮
            enterButton.isHidden = true
        }
    }
}
extension HRNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //1.滚动最后一屏 让视图删除
        let page = Int(scrollview.contentOffset.x / scrollview.bounds.width)
        
        //判断是否是最后一页
        if page == scrollview.subviews.count {
            removeFromSuperview()
        }
        
        //3.如果是倒数第二页显示按钮
        enterButton.isHidden = page != scrollview.subviews.count - 1
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //一旦滚动就是隐藏按钮 
        enterButton.isHidden = true
        //计算当前的偏移量
         let page = Int(scrollview.contentOffset.x / scrollview.bounds.width + 0.5)
        
        //设置分页控件
        pageControl.currentPage = page
        
        //分页控件的隐藏
        pageControl.isHidden = (page == scrollview.subviews.count)
    }
}
